import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function POST(req: NextRequest) {
  try {
    const authorId = getUserId(req);
    if (!authorId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { content, imageUrl } = await req.json();

    if (!content) {
      return NextResponse.json({ error: '动态内容不能为空' }, { status: 400 });
    }

    const newMoment = await prisma.moment.create({
      data: {
        authorId,
        content,
        imageUrl,
      },
      include: {
        author: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
        _count: {
          select: { likes: true },
        }
      },
    });

    const response = {
      ...newMoment,
      isLikedByMe: false, // 不能给自己点赞
    };

    return NextResponse.json(response, { status: 201 });
  } catch (error) {
    console.error('发布动态失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

export async function GET(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const cursor = searchParams.get('cursor');
    const limit = parseInt(searchParams.get('limit') || '10', 10);

    // 1. 获取好友列表
    const friendships = await prisma.friend.findMany({
      where: {
        status: 'ACCEPTED',
        OR: [{ userId: userId }, { friendId: userId }],
      },
    });
    const friendIds = friendships.map((f) => f.userId === userId ? f.friendId : f.userId);
    const authorIds = [userId, ...friendIds]; // 时间线包含自己和好友

    // 2. 查询动态
    const moments = await prisma.moment.findMany({
      take: limit,
      ...(cursor && {
        skip: 1,
        cursor: { id: cursor },
      }),
      where: {
        authorId: {
          in: authorIds,
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        author: {
          select: { id: true, username: true, avatar: true },
        },
        _count: {
          select: { likes: true },
        },
      },
    });
    
    // 3. 检查当前用户是否对这些动态点赞
    const momentIds = moments.map((m) => m.id);
    const userLikes = await prisma.momentLike.findMany({
      where: {
        userId: userId,
        momentId: { in: momentIds },
      },
    });
    const likedMomentIds = new Set(userLikes.map((like) => like.momentId));

    const momentsWithLikeStatus = moments.map((moment) => ({
      ...moment,
      isLikedByMe: likedMomentIds.has(moment.id),
    }));

    let nextCursor = null;
    if (moments.length === limit) {
      nextCursor = moments[limit - 1].id;
    }

    return NextResponse.json({
      moments: momentsWithLikeStatus,
      nextCursor,
    });

  } catch (error) {
    console.error('获取动态列表失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 